<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Ploy4J - 执行部署</title>
    <meta name="_csrf" th:content="${_csrf?.token}"/>
    <meta name="_csrf_header" th:content="${_csrf != null ? _csrf.headerName : ''}"/>
    <link rel="icon" href="/img/favicon.ico" type="image/x-icon">
    <!-- 引入Bootstrap图标 -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
</head>
<body>
    <div class="goploy-panel ploy4j-page-content">
        <!-- 页面标题和操作区 -->
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2><i class="bi bi-rocket-takeoff me-2"></i>执行部署</h2>
            <div>
                <a th:href="@{/deploy/jobs}" class="btn btn-outline-primary btn-sm">
                    <i class="bi bi-list-ul me-1"></i>查看部署历史
                </a>
            </div>
        </div>
        
        <!-- 提示消息 -->
        <div th:if="${deploymentSuccess}" class="alert alert-success d-flex align-items-center" role="alert">
            <i class="bi bi-check-circle-fill me-2"></i>
            <div>部署命令已成功提交并执行完毕 (请查看下方日志详情)。</div>
        </div>
        <div th:if="${deploymentError}" class="alert alert-danger d-flex align-items-center" role="alert">
            <i class="bi bi-exclamation-triangle-fill me-2"></i>
            <div>部署失败 (请查看下方日志详情)。</div>
        </div>

        <!-- 部署配置卡片 -->
        <div class="card mb-4 shadow-sm">
            <div class="card-header bg-primary bg-opacity-10">
                <h5 class="mb-0"><i class="bi bi-gear-fill me-2"></i>部署配置</h5>
            </div>
            <div class="card-body">
                <!-- 部署表单 -->
                <form th:action="@{/deploy/trigger-from-form}" method="post" id="deploymentForm" class="needs-validation" novalidate>
                    <div class="row">
                        <!-- 选择Git仓库 -->
                        <div class="col-md-6 mb-3">
                            <label for="gitRepoConfigId" class="form-label fw-bold">
                                <i class="bi bi-git me-1"></i>选择Git仓库配置
                                <span class="text-danger">*</span>
                            </label>
                            <select id="gitRepoConfigId" name="gitRepoConfigId" class="form-select" required>
                                <option value="">-- 请选择项目 --</option>
                                <option th:each="repo : ${gitRepos}" 
                                        th:value="${repo.id}" 
                                        th:text="${repo.projectName}" 
                                        th:attr="data-default-branch=${repo.defaultBranch || ''}">
                                </option>
                            </select>
                            <div class="invalid-feedback">请选择Git仓库</div>
                            <small class="form-text text-muted">选择要部署的源代码仓库</small>
                        </div>
                        
                        <!-- 选择服务器 -->
                        <div class="col-md-6 mb-3">
                            <label for="serverConfigId" class="form-label fw-bold">
                                <i class="bi bi-hdd-rack-fill me-1"></i>选择目标服务器配置
                                <span class="text-danger">*</span>
                            </label>
                            <select id="serverConfigId" name="serverConfigId" class="form-select" required>
                                <option value="">-- 请选择服务器 --</option>
                                <option th:each="server : ${servers}" 
                                        th:value="${server.id}" 
                                        th:text="${server.name + ' (' + server.host + ':' + server.port + ')'}">
                                </option>
                            </select>
                            <div class="invalid-feedback">请选择目标服务器</div>
                            <small class="form-text text-muted">选择要部署到的目标服务器</small>
                        </div>
                    </div>
                    
                    <!-- 分支选择 -->
                    <div class="mb-3">
                        <label for="branchName" class="form-label fw-bold">
                            <i class="bi bi-diagram-3-fill me-1"></i>分支名称
                        </label>
                        <div class="input-group">
                            <span class="input-group-text">Branch</span>
                            <input type="text" class="form-control" id="branchName" name="branchName" 
                                   placeholder="留空将使用Git仓库配置的默认分支">
                        </div>
                        <small id="defaultBranchHelp" class="form-text text-muted">
                            当前选择仓库的默认分支: <span id="selectedDefaultBranch">-</span>
                        </small>
                    </div>
                    
                    <!-- 部署选项 -->
                    <div class="mb-3">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="skipTests" name="skipTests" value="true" checked>
                            <label class="form-check-label" for="skipTests">跳过测试</label>
                        </div>
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="forceUpdate" name="forceUpdate" value="true">
                            <label class="form-check-label" for="forceUpdate">强制更新（即使没有代码变更）</label>
                        </div>
                    </div>
                    
                    <!-- 提交按钮 -->
                    <div class="d-grid gap-2 d-md-flex justify-content-md-center mt-4">
                        <button type="submit" class="btn btn-primary btn-lg px-4" id="deployButton">
                            <i class="bi bi-rocket-takeoff-fill me-2"></i>开始部署
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <!-- 部署日志卡片 -->
        <div class="card shadow-sm">
            <div class="card-header bg-dark bg-opacity-10 d-flex justify-content-between align-items-center">
                <h5 class="mb-0"><i class="bi bi-terminal-fill me-2"></i>部署日志</h5>
                <button class="btn btn-sm btn-outline-secondary" id="clearLogBtn" title="清空日志">
                    <i class="bi bi-trash"></i>
                </button>
            </div>
            <div class="card-body p-0">
                <div class="log-container bg-dark bg-opacity-10 p-3">
                    <pre id="deploymentLogOutput" class="mb-0 text-dark" style="max-height: 400px; overflow-y: auto; white-space: pre-wrap; font-family: 'Courier New', monospace;" th:text="${deploymentLog}">部署日志将显示在这里...</pre>
                </div>
            </div>
        </div>
    </div>

    <script>
    // 确保initDeploymentForm函数在全局作用域中定义
    window.initDeploymentForm = function() {
        console.log("正在初始化部署表单...");
        
        // 使用立即执行函数封装功能模块
        const DeploymentForm = (function() {
            // 私有变量
            const csrfToken = document.querySelector('meta[name="_csrf"]')?.getAttribute('content') || '';
            const csrfHeader = document.querySelector('meta[name="_csrf_header"]')?.getAttribute('content') || '';
            
            // DOM元素缓存
            const elements = {
                form: document.getElementById('deploymentForm'),
                gitRepoSelect: document.getElementById('gitRepoConfigId'),
                serverSelect: document.getElementById('serverConfigId'),
                branchName: document.getElementById('branchName'),
                skipTests: document.getElementById('skipTests'),
                forceUpdate: document.getElementById('forceUpdate'),
                deployButton: document.getElementById('deployButton'),
                defaultBranchSpan: document.getElementById('selectedDefaultBranch'),
                logOutput: document.getElementById('deploymentLogOutput'),
                clearLogBtn: document.getElementById('clearLogBtn')
            };
            
            // 初始化表单验证
            function initFormValidation() {
                if (!elements.form) return;
                
                elements.form.addEventListener('submit', function(event) {
                    if (!this.checkValidity()) {
                        event.preventDefault();
                        event.stopPropagation();
                    }
                    
                    this.classList.add('was-validated');
                    
                    // 添加正在部署提示
                    if (this.checkValidity()) {
                        if (elements.deployButton) {
                            elements.deployButton.disabled = true;
                            elements.deployButton.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 正在部署...';
                        }
                        
                        if (elements.logOutput) {
                            elements.logOutput.textContent = '正在启动部署流程，请稍候...';
                        }
                        
                        // 自动滚动到日志区域
                        setTimeout(() => {
                            const logContainer = elements.logOutput?.parentElement;
                            if (logContainer) {
                                logContainer.scrollIntoView({ behavior: 'smooth', block: 'start' });
                            }
                        }, 500);
                    }
                });
            }
            
            // 初始化Git仓库选择变更处理
            function initGitRepoChange() {
                if (!elements.gitRepoSelect || !elements.defaultBranchSpan) return;
                
                elements.gitRepoSelect.addEventListener('change', function() {
                    const selectedOption = this.options[this.selectedIndex];
                    const defaultBranch = selectedOption.dataset.defaultBranch || '-';
                    elements.defaultBranchSpan.textContent = defaultBranch;
                    
                    // 如果没有手动输入分支，则填入默认分支
                    if (elements.branchName && !elements.branchName.value && defaultBranch !== '-') {
                        elements.branchName.value = defaultBranch;
                    }
                    
                    validateForm();
                });
            }
            
            // 初始化服务器选择变更处理
            function initServerChange() {
                if (!elements.serverSelect) return;
                
                elements.serverSelect.addEventListener('change', function() {
                    validateForm();
                });
            }
            
            // 初始化日志清除按钮
            function initClearLogButton() {
                if (!elements.clearLogBtn || !elements.logOutput) return;
                
                elements.clearLogBtn.addEventListener('click', function() {
                    elements.logOutput.textContent = '日志已清空...';
                });
            }
            
            // 验证表单
            function validateForm() {
                if (!elements.form) return;
                
                // 检查Git仓库选择
                if (elements.gitRepoSelect) {
                    if (elements.gitRepoSelect.value) {
                        elements.gitRepoSelect.classList.add('is-valid');
                        elements.gitRepoSelect.classList.remove('is-invalid');
                    } else {
                        elements.gitRepoSelect.classList.add('is-invalid');
                        elements.gitRepoSelect.classList.remove('is-valid');
                    }
                }
                
                // 检查服务器选择
                if (elements.serverSelect) {
                    if (elements.serverSelect.value) {
                        elements.serverSelect.classList.add('is-valid');
                        elements.serverSelect.classList.remove('is-invalid');
                    } else {
                        elements.serverSelect.classList.add('is-invalid');
                        elements.serverSelect.classList.remove('is-valid');
                    }
                }
                
                // 更新部署按钮状态
                updateDeployButtonState();
            }
            
            // 更新部署按钮状态
            function updateDeployButtonState() {
                if (!elements.deployButton) return;
                
                const gitRepoValid = elements.gitRepoSelect && elements.gitRepoSelect.value;
                const serverValid = elements.serverSelect && elements.serverSelect.value;
                
                if (gitRepoValid && serverValid) {
                    elements.deployButton.disabled = false;
                } else {
                    elements.deployButton.disabled = true;
                }
            }
            
            // 监控表单输入变化
            function initFormInputMonitoring() {
                if (!elements.form) return;
                
                const formControls = elements.form.querySelectorAll('input, select');
                formControls.forEach(control => {
                    control.addEventListener('change', validateForm);
                    control.addEventListener('input', validateForm);
                });
            }
            
            // 监控部署日志
            function initDeploymentLogMonitoring() {
                if (!elements.logOutput) return;
                
                // 检查页面是否包含部署成功或失败的消息
                const successMsg = document.querySelector('.alert-success');
                const errorMsg = document.querySelector('.alert-danger');
                
                if (successMsg || errorMsg) {
                    // 自动滚动到日志区域
                    setTimeout(() => {
                        const logContainer = elements.logOutput.parentElement;
                        if (logContainer) {
                            logContainer.scrollIntoView({ behavior: 'smooth', block: 'start' });
                        }
                    }, 500);
                }
            }
            
            // 初始化函数
            function init() {
                console.log('初始化部署表单模块...');
                
                // 初始化表单验证
                initFormValidation();
                
                // 初始化Git仓库选择变更处理
                initGitRepoChange();
                
                // 初始化服务器选择变更处理
                initServerChange();
                
                // 初始化日志清除按钮
                initClearLogButton();
                
                // 初始化表单输入监控
                initFormInputMonitoring();
                
                // 初始化部署日志监控
                initDeploymentLogMonitoring();
                
                // 初始验证
                validateForm();
            }
            
            // 返回公共API
            return {
                init: init
            };
        })();
        
        // 初始化部署表单模块
        DeploymentForm.init();
    };

    // 如果页面已经加载完毕，则直接初始化
    if (document.readyState === 'complete' || document.readyState === 'interactive') {
        window.initDeploymentForm();
    } else {
        // 否则等待DOM加载完成后初始化
        document.addEventListener('DOMContentLoaded', window.initDeploymentForm);
    }
    </script>
</body>
</html> 